package com.yunkeji.common.msg.utils;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yunkeji.common.msg.bo.HttpResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/** Http 工具类 */
@Slf4j
@Component
public class MsgHttpUtils {

    /**
     * 普通消息发送
     *
     * @param url
     * @param paramObj
     * @return
     */
    public static HttpResp sendNormalPostHttp(String url, JSONObject paramObj) {
        String body = paramObj.toStringPretty();
        log.info("请求地址:{},请求参数:{}", url, paramObj);
        try {
            HttpResponse execute = HttpUtil.createPost(url).body(body).execute();
            int status = execute.getStatus();
            if (status != 200) {
                log.error("请求异常,url:{},状态码:{}", url, status);
                return HttpResp.builder().status(status).jsonData(JSONUtil.createObj()).build();
            } else {
                String res = execute.body();
                log.info("请求成功,url:{},状态码:{},响应:{}", url, status, JSONUtil.toJsonPrettyStr(res));
                return HttpResp.builder().status(status).jsonData(JSONUtil.parseObj(res)).build();
            }
        } catch (IORuntimeException e) {
            log.error("请求IO异常:{}", e.getMessage());
            return HttpResp.builder().status(500).jsonData(JSONUtil.createObj()).build();
        } catch (Exception e) {
            log.error("请求异常:{}", e.getMessage(), e);
            return HttpResp.builder().status(500).jsonData(JSONUtil.createObj()).build();
        }
    }
}
